﻿CREATE FUNCTION dbo.f_PriorRepos
(@LoanID int,@Pulled bit,@Now datetime)
RETURNS sql_variant WITH SCHEMABINDING BEGIN 

DECLARE @Ret datetime

--IF @Now IS NULL AND @Pulled <> 1	RETURN '1/1/1900'
IF ISNULL(@Pulled,0) = 0	RETURN NULL

SELECT @Ret = MAX(LastDate)
FROM dbo.v_TradeReferences WHERE LoanID = @LoanID AND IsRepo = 1

IF @Now IS NULL RETURN @Ret

RETURN  ISNULL(DATEDIFF(mm,@Ret,@Now),NULL)

END

